using B.S.RbacData.Infrastructure;
using MediatR;
using SupplierCustomerManagement.Domain.Entities;
using B.S.RbacData.ErrorCode;
using SupplierCustomerManagement.Write.API.Applications.Commands.bankaccounts;

namespace SupplierCustomerManagement.Write.API.Applications.CommandHandlters.bankaccounts
{
    /// <summary>
    /// 删除银行账户命令处理器
    /// </summary>
    public class DeleteBankAccountCommandHandler : IRequestHandler<DeleteBankAccountCommand, ApiResult<bool>>
    {
        private readonly IBaseRepository<BankAccount> _bankAccountRepository;
        private readonly ILogger<DeleteBankAccountCommandHandler> _logger;

        public DeleteBankAccountCommandHandler(
            IBaseRepository<BankAccount> bankAccountRepository,
            ILogger<DeleteBankAccountCommandHandler> logger)
        {
            _bankAccountRepository = bankAccountRepository;
            _logger = logger;
        }

        /// <summary>
        /// 处理删除银行账户命令
        /// </summary>
        /// <param name="request">删除银行账户命令</param>
        /// <param name="cancellationToken">取消令牌</param>
        /// <returns>删除结果</returns>
        public async Task<ApiResult<bool>> Handle(DeleteBankAccountCommand request, CancellationToken cancellationToken)
        {
            try
            {
                _logger.LogInformation("开始删除银行账户，银行账户ID: {BankAccountId}", request.Id);

                // 查找要删除的银行账户
                var bankAccount =  _bankAccountRepository.GetAll().FirstOrDefault(x=>x.Id== request.Id);

                if (bankAccount == null || bankAccount.IsDeleted)
                {
                    _logger.LogWarning("未找到指定的银行账户，银行账户ID: {BankAccountId}", request.Id);
                    
                    return new ApiResult<bool>
                    {
                        code = ResultEnumCode.fails,
                        message = "未找到指定的银行账户",
                        data = false
                    };
                }

                // 软删除银行账户
                bankAccount.IsDeleted = true;
                bankAccount.UpdatedTime = DateTime.Now;
                bankAccount.UpdatedBy = 1; // 后续可以从当前用户上下文获取

                await _bankAccountRepository.UpdateAsync(bankAccount);

                _logger.LogInformation("成功删除银行账户，银行账户ID: {BankAccountId}, 账户号码: {AccountNumber}", 
                    request.Id, bankAccount.AccountNumber);

                return new ApiResult<bool>
                {
                    code = ResultEnumCode.Ok,
                    message = "删除银行账户成功",
                    data = true
                };
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除银行账户时发生异常，银行账户ID: {BankAccountId}", request.Id);
                
                return new ApiResult<bool>
                {
                    code = ResultEnumCode.fails,
                    message = $"删除银行账户时发生异常: {ex.Message}",
                    data = false
                };
            }
        }
    }
}